﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net 前台页面控制器        ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Wedn.Net.Common;
using Wedn.Net.Controller.Base;
using Wedn.Net.Model;
using Wedn.Net.Utility;

namespace Wedn.Net.Controller
{
    /// <summary>
    /// 异步请求控制器
    /// </summary>
    public class AjaxController : FrontBaseController
    {
        #region 登录校验 +ContentResult Login(string login, string password, bool isRemember)
        /// <summary>
        /// 登录校验
        /// </summary>
        /// <param name="login">登录名</param>
        /// <param name="password">密码</param>
        /// <param name="isRemember">是否记住密码</param>
        /// <returns>登录标识</returns>
        [HttpPost]
        public ContentResult Login(string login, string password, bool isRemember)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
                Response.End();//用户名密码为空
            User user;
            var loginRes = BllInstance.UserManager.Login(login, password, out user);
            if (loginRes == LoginResult.Success)
            {
                SessionHelper.AddSession("CurrentUser", user);
                if (isRemember)
                    CookieHelper.SetCookie("URM", BllInstance.UserManager.GetEncryptUserInfo(user));
            }
            return Content(loginRes.ToString());
        }
        #endregion

        #region 登出控制器 +RedirectResult Logout()
        /// <summary>
        /// 登出控制器
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public RedirectResult Logout()
        {
            //清除Cookie和Session
            SessionHelper.RemoveSession("CurrentUser");
            CookieHelper.RemoveCookie("URM");
            return Redirect(Url.Action("Index", "Login"));
        }
        #endregion

        #region 发布文章请求处理 +ActionResult PublishPost(Post entity)
        /// <summary>
        /// 发布文章请求处理
        /// </summary>
        /// <param name="entity">文章实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult PublishPost(Post entity)
        {
            //return null;
            #region 处理发表物
            if (entity.Id == 0)
            {
                //新增文章
                entity.PubDate = entity.Modified;
                entity.Pinged = string.Empty;
                entity = BllInstance.PostManager.Insert(entity);//向数据库上下文插入文章实体
                //更新文章数
                BllInstance.OptionManager.UpdateValue("site_post_count", (Setting.SitePostCount + 1).ToString());
            }
            else
            {
                //修改文章
                entity.Modified = entity.PubDate;
                BllInstance.PostManager.Update(entity);
            }
            int rows = BllInstance.DbSaveChanges();//同步数据库上下文变化到数据库 
            #endregion

            //创建关系对象集合
            var relations = new List<Relation>();
            var terms = BllInstance.TermManager.Select(t => true).ToList();

            //#region 处理标签
            //string tag = entity.Tags;
            //if (!string.IsNullOrEmpty(tag))
            //{
            //    string[] tags = tag.Split(new[] { ',', '|', '，' }, StringSplitOptions.RemoveEmptyEntries);
            //    //获取已存在的标签数据
            //    IList<Term> existTags = terms.Where(t => t.Type == (int)TermType.PostTag && tags.Contains(t.Name)).ToList();
            //    IList<int> tagIds = new List<int>();//existTags.Select(t => t.Id).ToList();
            //    IList<string> existTagsName = new List<string>(); //existTags.Select(t => t.Name).ToArray();
            //    //更新标签文章数量
            //    foreach (var t in existTags)
            //    {
            //        t.Count++;
            //        tagIds.Add(t.Id);
            //        existTagsName.Add(t.Name);
            //        BllInstance.TermManager.Update(t);//更新文章数
            //    }
            //    //创建新标签集合
            //    IList<Term> newTags = tags.Where(t => !existTagsName.Contains(t))
            //                              .Select(t => new Term { Name = t, Description = string.Empty, ParentId = -1, Slug = string.Empty, Count = 1 })
            //                              .ToList();
            //    BllInstance.TermManager.Insert(newTags.ToArray());//向数据库上下文插入标签实体
            //    rows += BllInstance.DbSaveChanges();//同步数据库上下文变化到数据库
            //    foreach (var t in newTags)
            //    {
            //        tagIds.Add(t.Id);
            //    }
            //    relations.AddRange(tagIds.Select(i => new Relation { ObjectId = entity.Id, ObjectType = (int)RelationObjectType.Post, TermId = i }).ToList());
            //    //更新标签数
            //    BllInstance.OptionManager.UpdateValue("site_tag_count", (Setting.SiteTagCount + newTags.Count).ToString());
            //}
            //#endregion

            //#region 处理分类关系
            //string category = entity.Categorys;
            //if (!string.IsNullOrEmpty(category) && category != "-1")
            //{
            //    int[] categoryIds = category.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
            //                               .Select(i => i.ToInt(0))
            //                               .Where(i => i != 0)
            //                               .ToArray();
            //    relations.AddRange(categoryIds.Select(i => new Relation { ObjectId = entity.Id, ObjectType = (int)RelationObjectType.Post, TermId = i }).ToList());
            //    var categorys = BllInstance.TermManager.Select(c => categoryIds.Contains(c.Id));
            //    foreach (var cat in categorys)
            //    {
            //        cat.Count++;
            //        BllInstance.TermManager.Update(cat);//更新文章数
            //    }
            //}
            //else if (category == "-1")
            //{
            //    var cat = BllInstance.TermManager.SelectSingle(c => c.Id == 1);
            //    cat.Count++;
            //    BllInstance.TermManager.Update(cat);
            //    relations.Add(new Relation { ObjectId = entity.Id, ObjectType = (int)RelationObjectType.Post, TermId = 1 });
            //}
            //#endregion

            //保存关系
            if (relations.Count > 0)
            {
                var delRel = BllInstance.RelationManager.Select(r => r.ObjectId == entity.Id && r.ObjectType == (int)RelationObjectType.Post);
                foreach (var rel in delRel)
                {
                    Term term = terms.FirstOrDefault(t => t.Id == rel.TermId);
                    term.Count--;
                    BllInstance.TermManager.Update(term);
                    BllInstance.RelationManager.Delete(rel);
                }
                foreach (var rel in relations)
                    BllInstance.RelationManager.Insert(rel);//向数据库上下文插入关系实体
                rows += BllInstance.DbSaveChanges();//同步数据库上下文变化到数据库 
            }
            return Json(new { Status = 0, PostId = entity.Id, PostLink = Url.Action("Detail", "Blog", new { item = entity.Slug }) });
        }
        #endregion

        #region 获取百度MAPAPI信息 +ContentResult GetMarker()
        /// <summary>
        /// 获取百度MAPAPI信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetMarker()
        {
            return Content(HttpHelper.Get("http://api.map.baidu.com/location/ip", "ak=BDb449eafd7aacbfff666c48f08ce364&ip=" + RequestHelper.IPAddress));
        }
        #endregion

        #region 异步评论 +JsonResult Comment(Comment entity)
        /// <summary>
        /// 异步评论
        /// </summary>
        /// <param name="entity">评论实体</param>
        /// <returns></returns>
        public JsonResult Comment(Comment entity)
        {

            if (string.IsNullOrEmpty(entity.AuthorName) || string.IsNullOrEmpty(entity.AuthorEmail))
                return Json(new { Status = false, Message = "请完善评论信息" });
            entity.PubDate = DateTime.Now;
            entity.Status = (int)CommentStatus.Awaiting;
            entity.UserId = -1;

            BllInstance.CommentManager.Insert(entity);
            var post = BllInstance.PostManager.SelectSingle(p => p.Id == entity.PostId);
            post.CommentCount++;
            return Json(BllInstance.PostManager.Update(true, post) > 0
                ? new { Status = true, Message = "评论成功" }
                : new { Status = false, Message = "评论失败，请稍候再试" });
        }
        #endregion
    }
}
